package com.siwei.mes.sync.erp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.config.UidUtils;
import com.siwei.mes.entity.ExperimentIronMarkRel;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.erp.RwdextraInfo;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.ExperimentSampleSmoke;
import com.siwei.mes.entity.experiment.ExperimentSampleTestProject;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.ExperimentIronMarkRelMapper;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.experiment.ExperimentSampleSmokeMapper;
import com.siwei.mes.mapper.experiment.ExperimentSampleTestProjectMapper;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.sync.erp.service.GenConcreteService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成抗氯离子试验委托-铁标
 *
 * @Description: 生成抗氯离子试验委托-铁标
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/7/7 16:45
 */
@Service
public class GenKllzTieBiaoExperimentService extends GenConcreteService {
    private static final Logger log = LoggerFactory.getLogger("erp");
    @Resource
    private ExperimentService experimentService;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private ExperimentSampleTestProjectMapper experimentSampleTestProjectMapper;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;
    @Resource
    private ExperimentIronMarkRelMapper experimentIronMarkRelMapper;

    /**
     * 生成抗氯离子试验委托-铁标
     *
     * @param rwdextra           任务单
     * @param itemorder          小票
     * @param testProjectInfoMap 试验委托信息
     * @return
     */
    public Long genExperiment(Rwdextra rwdextra, Itemorder itemorder, Map<String, TestProjectInfo> testProjectInfoMap) {
        try {
            log.info("铁标-生成混凝土抗氯离子开始，任务单号：【{}】，小票id；【{}】", rwdextra.getFrwdh(), itemorder.getItid());

            /**判断这个任务单是否有铁标抗氯离子*/
            ExperimentIronMarkRel experimentIronMarkRel = experimentIronMarkRelMapper.selectByFrwdh(rwdextra.getFrwdh());
            if (experimentIronMarkRel != null) {
                log.info("铁标-任务单：【{}】，小票id：【{}】，已经生成了抗氯离子试验委托，不需要再次生成！对应试验委托id：【{}】", rwdextra.getFrwdh(), itemorder.getItid(), experimentIronMarkRel.getExperimentId());
                return experimentIronMarkRel.getExperimentId();
            }

            RwdextraInfo rwdextraInfo = rwdextra.getRwdextraInfo();
            if (rwdextraInfo == null) {
                log.info("铁标-混凝土生成抗氯离子对应任务单扩展信息为空，暂不生成，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }
            String tpz = itemorder.getTpz();
            if (StringUtils.isBlank(tpz)) {
                log.info("铁标-混凝土砼品种为空，暂不生成，砼品种：【{}】，任务单：【{}】，小票id：【{}】", tpz, rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }
            /**这里需要CL  比如C30CL3.0*/
            String kllz = rwdextra.getRwdextraInfo().getKllz();

            log.info("铁标-混凝土抗氯离子对应的砼品种为：【{}】，氯离子含量：【{}】", tpz, kllz);

            String fPhbNo = rwdextra.getPhbshow();//配合比
            String fGcmc = rwdextraInfo.getFGcmc();//工程名称
            String ksdj = rwdextraInfo.getKsdj();

            log.info("铁标-开始组装混凝土【抗氯离子】对应试验委托，抗氯离子：【{}】，配合比号：【{}】,砼品种：【{}】，工程名称：【{}】，任务单号：【{}】，小票id：：【{}】",
                    kllz, fPhbNo, tpz, fGcmc, rwdextra.getFrwdh(), itemorder.getItid());


            List<String> testCodeList = new ArrayList<>();
            testCodeList.add(TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode());
            testCodeList.add(TestProjectEnum.CONCRETE_PARAM_JHL.getCode());

            /**委托试验名称*/
            Set<String> entrustExperimentSet = new HashSet<>();
            /**试验项目code集合*/
            Set<String> testProjectCodeList = new HashSet<>();

            /**获取所有试验项目配置*/
            List<TestProjectInfo> testProjectInfoList = new ArrayList<>();

            for (String testCode : testCodeList) {
                TestProjectInfo projectInfo = testProjectInfoMap.get(testCode);
                if (projectInfo == null) {
                    continue;
                }
                testProjectInfoList.add(projectInfo);
                testProjectCodeList.add(projectInfo.getTestCode());
                entrustExperimentSet.add(projectInfo.getTestName());
            }

            String entrustExperiment = entrustExperimentSet.stream().map(String::valueOf).collect(Collectors.joining(","));

            /**新增混凝土试验台账*/
            Experiment experiment = experimentService.getExperimentInfoByItemOrderInfo(itemorder, CheckEnum.BATCH.getCode(), entrustExperiment, testProjectCodeList);
            experiment.setPhb(fPhbNo);
            experiment.setKsdj(ksdj);

            /**组装物料相关信息*/
            super.payloadMaterialsInfo(itemorder.getTpz(), experiment);
            /** 协会相关信息，通过企业配置信息赋值**/
            String sampleNo = UidUtils.genNoNumberToYearStr(GenerateCodeEnum.KLLZ_SAMPLENO.getCode(), "%06d", "12");
            String consignId = UidUtils.genNoNumberToYearStr(GenerateCodeEnum.KLLZ_CONSIGNID.getCode(), "%06d", "12");
            String kllzReportId = GenerateCodeEnum.KLLZ_REPORTID.getCode() + DateHelper.getYear() + UidUtils.genNoNumber(GenerateCodeEnum.KLLZ_REPORTID.getCode(), "%05d");
            experiment.setSampleNo(sampleNo);
            experiment.setReportNo(kllzReportId);
            experiment.setReportDate(new Date());
            experiment.setCreateType(CreateTypeEnum.DEFAULT_CHECK.getCode()).setCreateCheckType(CheckTypeEnum.DEFAULT_CHECK.getCode());
            experimentMapper.insertSelective(experiment);
            Long experimentId = experiment.getId();

            ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
            if (shxhInfo == null) {
                //新增对应关系
                ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata().setSampleId(sampleNo)
                        .setSampleNo(sampleNo).setConsignId(consignId).setExperimentId(experimentId);
                shxhSynchronizedataMapper.insertSelective(synchronizedata);
            } else {
                shxhInfo.setSampleId(sampleNo)
                        .setSampleNo(sampleNo).setConsignId(consignId).setExperimentId(experimentId);
                shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
            }

            if (!testProjectCodeList.isEmpty()) {
                List<ExperimentDetail> detailList = new ArrayList<>();
                /**查询所有试验项目信息*/
                for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                    ExperimentDetail detail = new ExperimentDetail();
                    detail.setExperimentId(experiment.getId());
                    detail.setCheckType(CheckEnum.BATCH.getCode());
                    detail.erpInit(true);
                    detail.setTestProjectCode(testProjectInfo.getTestCode());
                    detail.setTestProjectName(testProjectInfo.getTestName());
                    detail.setObjJson(testProjectInfo.getObjJson());
                    detailList.add(detail);
                }
                if (!detailList.isEmpty()) {
                    /**生成对应试验台账详情信息*/
                    experimentDetailMapper.insertList(detailList);
                }

                /**这里要过滤掉抗渗等级  抗渗等级是有压试块的*/
                List<String> filterTestProjectCode = new ArrayList<>();
                filterTestProjectCode.add(TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode());
                filterTestProjectCode.add(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
                /**这里要查询不需要过滤的*/
                for (String testCode : testCodeList) {
                    if (!filterTestProjectCode.contains(testCode)) {
                        /**新增对应快检的抽样信息  对应快检的所有的项目集合只有一条数据 */
                        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
                        sampleSmoke.setId(null);
                        sampleSmoke.erpInit(true);
                        sampleSmoke.setExperimentId(experiment.getId());
                        sampleSmoke.setSampleTime(new Date());
                        sampleSmoke.setIsTestBlock(0);// 是否是试块 1-是 0-不是
                        sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
                        sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());

                        StringBuilder testProjectCode = new StringBuilder();
                        StringBuilder testProjectName = new StringBuilder();

                        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                            testProjectCode.append(testProjectInfo.getTestCode()).append(",");
                            testProjectName.append(testProjectInfo.getTestName()).append(",");
                        }
                        if (testProjectCode.length() > 0) {
                            String code = testProjectCode.deleteCharAt(testProjectCode.length() - 1).toString();
                            sampleSmoke.setTestProjectCode(code);
                        }
                        if (testProjectName.length() > 0) {
                            String name = testProjectName.deleteCharAt(testProjectName.length() - 1).toString();
                            sampleSmoke.setTestProjectName(name);
                            sampleSmoke.setSampleUse(name);
                        }
                        experimentSampleSmokeMapper.insertSelective(sampleSmoke);
                    }
                }
            }

            /**如果是批检 并且在抽样试验项目配置中 有记录 直接生成对应的抽样记录 pk_experiment_sample_test_project*/
            List<ExperimentSampleSmoke> sampleSmokeList = new ArrayList<>();
            List<ExperimentSampleTestProject> sampleTestProjectList = experimentSampleTestProjectMapper.selectByTestProjectCodeList(testProjectCodeList);
            for (ExperimentSampleTestProject sampleTestProject : sampleTestProjectList) {
                Integer genNumber = sampleTestProject.getGenNumber();// 生成的条数
                JSONObject genJson = sampleTestProject.getGenJson();// 生成对应的json
                if (genJson.isEmpty() || genNumber == null || genNumber == 0) {
                    continue;
                }
                ExperimentSampleSmoke sampleSmoke = this.getExperimentSampleSmoke(sampleTestProject, experiment, null);
                sampleSmokeList.add(sampleSmoke);
            }
            /**保存抽样信息*/
            if (!sampleSmokeList.isEmpty()) {
                experimentSampleSmokeMapper.insertList(sampleSmokeList);
            }
            /**插入试验台账对应小票数据和试验台账对应ERP任务单记录*/
            super.insertExperimentRelatedRecords(experimentId, itemorder.getItid(), rwdextra.getFrwdh());
            /**修改试验台账的代表数量*/
            super.updateExperimentBehalfNumber(experimentId);
            log.info("铁标-生产混凝土抗氯离子完成！对应试验委托id：【{}】", experimentId);

            /**新增对应管理关系*/
            ExperimentIronMarkRel ironMarkRel = new ExperimentIronMarkRel();
            ironMarkRel.setFrwdh(rwdextra.getFrwdh());
            ironMarkRel.setExperimentId(experimentId);
            experimentIronMarkRelMapper.insertSelective(ironMarkRel);
            return experimentId;
        } catch (Exception e) {
            super.handleException("铁标-混凝土生成抗氯离子失败", e);
            return null;
        }
    }
}
